<?php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use JWTAuth;

class CheckPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {

            //获取当前控制器
            $actions = explode('\\', \Route::current()->getActionName());

            $modelName = $actions[count($actions) - 2] == 'Controllers' ? null : $actions[count($actions) - 2];
            $func = explode('@', $actions[count($actions) - 1]);
            //获取当前控制器
            $controllerName = $func[0];
            //获取当前方法
            $actionName = $func[1];

            //获取当前用户信息
            //获取当前用户
            $user = JWTAuth::parseToken()->toUser();


            //判断是否是超级管理员
            if ($user->hasRole('super_admin')) {
                return $next($request);
            }

            //获取用户拥有的权限
            $permission = $user->getPermissionsViaRoles()->toArray();
            $permission = array_column($permission, 'name');
            //判断是否有权限
            if (in_array($controllerName, $permission)) {
                return $next($request);
            }

            // 没有权限则返回到403页面
            return response()->json([
                'code' => 403,
                'data' => '您没有权限访问'
            ]);
            // return $next($request);

        } catch (\Exception $e) {

        }


    }
}
